package newkfp;

import Beans.FactoryList;
import Beans.Country_Factory;
import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;

import java.io.Serializable;
import java.util.*;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "countryController")
@SessionScoped
public class CountryController implements Serializable {

    Loger loger;
    @EJB
    private newkfp.LogFacade logFacade;
    List<Country_Factory> country_FactoryLists = new ArrayList<Country_Factory>();
    private DataModel factoryList = null;
    private Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
    private Country current;
    private DataModel items = null;
    @EJB
    private newkfp.CountryFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int fId;

    public CountryController() {
        loger = new Loger(getLogFacade());
    }

    public Map<Long, Boolean> getChecked() {
        this.checked = checked;
        System.out.println(" setting in map");
        for (Map.Entry<Long, Boolean> entry : checked.entrySet()) {
            Long long1 = entry.getKey();
            Boolean boolean1 = entry.getValue();
            System.out.println(" " + long1 + "          bbbooooooooooo" + boolean1);
        }
        return checked;
    }

    public void setChecked(Map<Long, Boolean> checked) {
        this.checked = checked;
        for (Map.Entry<Long, Boolean> entry : checked.entrySet()) {
            Long long1 = entry.getKey();
            Boolean boolean1 = entry.getValue();
        }
    }

    public Country getSelected() {
        if (current == null) {
            current = new Country();
            selectedItemIndex = -1;
        }
        return current;
    }

    private CountryFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(getFacade().count()) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Country) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Country();
        selectedItemIndex = -1;
        recreateModel();
        return "List";
    }

    public String create() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CountryCreated"));
            loger.LogerString("اضافة دوله جديد", 0);
            return prepareList();
        } catch (Exception e) {
            loger.LogerString("خطاء في اضافة دوله جديد", 1);
            loger.LogerString("CountryController : Create : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Country) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CountryUpdated"));
            loger.LogerString(" تم تعديل دوله بنجاح", 0);
            return prepareList();
        } catch (Exception e) {
            loger.LogerString("خطاء في تعديل دوله", 1);
            loger.LogerString("CountryController : update : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Country) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        loger = new Loger(getLogFacade());
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CountryDeleted"));
            loger.LogerString("تم حذف الدوله بنجاح", 0);
        } catch (Exception e) {
            loger.LogerString("خطاء في حذف الدوله", 1);
            loger.LogerString("CountryController : Destroy : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
         pagination=null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Country.class)
    public static class CountryControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CountryController controller = (CountryController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "countryController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Country) {
                Country o = (Country) object;
                return getStringKey(o.getIdcountry());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CountryController.class.getName());
            }
        }
    }

    public PaginationHelper getFactoryPaginationHelper() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    List<Country> countrys = ejbFacade.getAllCountry();
                    for (Iterator it = countrys.iterator(); it.hasNext();) {
                        Country country = (Country) it.next();
                        List<FactoryList> factoryLists = new ArrayList<FactoryList>();
                        Collection<Factory> list = country.getFactoryCollection();
                        for (Iterator<Factory> it1 = list.iterator(); it1.hasNext();) {
                            Factory factory = it1.next();
                            FactoryList factoryList = new FactoryList();

                            // fill shadow been 
                            factoryList.setFactoryId(factory.getIdFactory());
                            factoryList.setFactoryName(factory.getFactoryName());


                            factoryLists.add(factoryList);
                        }

                        Country_Factory country_Factory = new Country_Factory();
                        country_Factory.setCountryID(country.getIdcountry());
                        country_Factory.setCountryName(country.getCountryName());
                        country_Factory.setFactoryList(factoryLists);
                        country_FactoryLists.add(country_Factory);
                    }

                    return new ListDataModel(country_FactoryLists);
                }
            };
        }
        return pagination;
    }

    public DataModel getFactoryList() {

        if (factoryList == null) {
            factoryList = getFactoryPaginationHelper().createPageDataModel();

        }
        return factoryList;

    }

    public int getFId() {
        return fId;
    }

    public void setFId(int fId) {
        this.fId = fId;
    }

    public String deleteSelected() {
        try {

            Iterator<Country> itr = items.iterator();
            while (itr.hasNext()) {
                Country expense = itr.next();
                if (checked.get(expense.getIdcountry())) {
                    System.out.println(" selected +++++++" + expense.getCountryName());
                }
            }

            return "List";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("DeleteError"));
            return "List";
        }
    }

    public static final String utf8Convert(String utf8String) throws
            java.io.UnsupportedEncodingException {
        byte[] bytes = new byte[utf8String.length()];
        for (int i = 0; i < utf8String.length(); i++) {
            bytes[i] = (byte) utf8String.charAt(i);
        }
        return new String(bytes, "UTF-8");
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }
}
